<script setup lang="ts">
  import { ref,watch } from 'vue';

  let user = ref({name:'张三',age:18,gender:'男'})  // ref定义对象类型

  function add(){
    user.value.age++;
  }

  function changeGender(){
    if(user.value.gender=='男'){
      user.value.gender='女'
    }else{
      user.value.gender='男'
    }
  }

  function changeUser(){
    user.value.name='李四';
    user.value.age=20;
    user.value.gender='男'
  }

  watch(()=>user.value.gender,(newValue,oldValue)=>{  // ()=>监听目标为对象的某个属性时
    console.log(`性别监听到了,改变前:${oldValue},改变后:${newValue}`)
  })

  watch(user,(newValue,oldValue)=>{
    console.log(`深度监听到了,改变前:${oldValue},改变后:${newValue}`) // 改变前和改变后都是同一个对象
  },{deep:true}) // 需定义深度监听

</script>
<template>
    <div class="home">
        <h2>姓名:{{user.name}}</h2>
        <h2>年龄:{{user.age}}</h2>
        <h2>性别:{{user.gender}}</h2>
        <button @click="add">年龄+1</button>
        <button @click="changeGender">改变性别</button>
        <button @click="changeUser">换个人</button>
    </div>
</template>
<style scoped>
  h2{
    color: cadetblue;
  }
</style>